<?php

namespace common\models;

use common\helpers\commonApi;
use common\helpers\UploadApi;
use common\helpers\ValidateApi;
use Yii;

/**
 * This is the model class for table "{{%collection_info}}".
 *
 * @property int $id
 * @property int|null $userid 用户id
 * @property string|null $username 收款人
 * @property string|null $wechat_number 微信号
 * @property string|null $phone 手机号
 * @property string|null $collection_code 收款码
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 */
class CollectionInfo extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%collection_info}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['username', 'wechat_number', 'phone', 'collection_code'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userid' => '用户id',
            'username' => '收款人',
            'wechat_number' => '微信号',
            'phone' => '手机号',
            'collection_code' => '收款码',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
        ];
    }

    /**
     * 设置
     * @param $userid
     * @param $data
     * @return array
     */
    public function edit($userid,$data)
    {
        $result = $this->verific($data,$userid);
        if (!$result['success']){
            return $result;
        }
        $model = self::findOne(['userid'=>$userid]);
        if (!$model){
            $model = new self();
        }
        $model->load($result['data'],'');
        $model->userid = $userid;
        if ($model->save()!==false){
            return commonApi::message('设置成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    public function verific($data,$userid)
    {
        if (empty($data['username'])){
            return commonApi::message('请输入收款人',false);
        }
        if (empty($data['wechat_number'])){
            return commonApi::message('请输入微信号',false);
        }
        if (empty($data['phone'])){
            return commonApi::message('请输入手机号',false);
        }
        if (!ValidateApi::isMobilePhone($data['phone'])){
            return commonApi::message('手机号错误',false);
        }
        if (empty($data['collection_code'])){
            return commonApi::message('请上传收款码',false);
        }
        if(!commonApi::isLink($data['collection_code'])){
            $upload = new UploadApi();
            $res = $upload->oss($data['collection_code'],'collection_'.$userid);
            if (!$res){
                return commonApi::message('上传海报失败',false);
            }
            $data['collection_code'] = $res;
        }
        return commonApi::message('ok',true,$data);
    }
}
